package main

import (
	"example-damo/lock"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"strconv"
	"time"
)

func main() {
	var pool *redis.Pool
	pool = &redis.Pool{
		MaxIdle:     10,  //最初的连接数量
		MaxActive:   0,   //连接池最大连接数量,（0表示自动定义），按需分配
		IdleTimeout: 300, //连接关闭时间 300秒 （300秒不使用自动关闭）
		Dial: func() (redis.Conn, error) {
			c, _ := redis.Dial("tcp", "r-bp1v3q1zerm2y5mz6npd.redis.rds.aliyuncs.com:6379")
			c.Do("AUTH", "peng_pre_redis663SC3H1K32g3b") //要连接的redis数据库
			return c, nil
		},
	}
	conn := pool.Get() //从连接池，取一个链接
	defer conn.Close()

	// 0. ping正常返回pong， 异常res is nil, err not nil
	res, err := conn.Do("ping")
	fmt.Printf("ping res=%v\n", res)
	if err != nil {
		fmt.Printf("ping err=%v\n", err.Error())
	}
	lock.RedigoClient = pool
	poolIndex := 1
	for {
		poolIndex++
		fmt.Println(poolIndex)
		go Do()
	}
}

func Do() {
	timeStamp := time.Now().Unix()
	redigoLock := lock.NewRedigoLock("test", strconv.Itoa(int(timeStamp)), 20, 40)
	ok, _ := redigoLock.TryLock()
	if ok {
		fmt.Println("start")
		fmt.Println("end")
		_ = redigoLock.Unlock()
	}
}
